<script setup lang="ts">
import ComponentsExcel from '@/components/ComponentsExcel.vue';
// import ComponentsExcel from '@/components/ComponentsEasyExcel.vue';
import { onMounted, onUnmounted, onBeforeMount, ref, type Ref } from "vue";
import type { SSEChatParams } from "../assets/utils/sse";
import { sseService } from "../assets/utils/sse";
import { setUrlParams } from "@/service/sseUrl";
import { useCounterStore } from './../stores/counter'
import { storeToRefs } from 'pinia';
import { decodeString } from '@/assets/utils/charEncoder';

let appId = 'E68891E79A84E695B0E68DAEE58C85' // 默认应用缩写（我的数据包
let appName: string = '我的数据包' // 默认应用名（我的数据包）
let mode = 'create'
let editFileId: string | undefined
let editFileName: string | undefined
let pathUrl: string | undefined = appId

let currentApp: {
    名称: string
    缩写: string
    路由?: string
    图标?: string
    类型?: string
}

onBeforeMount(() => {
    const counterStore = useCounterStore()
    const { openFileInfo } = storeToRefs(counterStore)
    const currentFile = openFileInfo.value
    console.log('当前文件参数信息', currentFile)
    if (currentFile && currentFile.appId && currentFile.appName) {
        appId = currentFile.appId
        appName = currentFile.appName
        mode = 'update'
        currentApp = {
              缩写: currentFile.appId,
              名称: currentFile.appName,
          }
        editFileName = currentFile.fileName
        editFileId = currentFile.fileId
        pathUrl = currentFile.pathUrl
    }
    openFileInfo.value = {}

    if (!currentApp) {
          currentApp = {
              名称: appName,
              缩写: appId,
          }
      }
      console.log('当前应用', currentApp, mode)
})

let fileData: Ref<any[] | undefined> = ref(undefined)
let sseData: Ref<any[] | undefined> = ref(undefined)

//see 链接
const sseServiceOpen = () => {
    console.log("尝试建立文件数据sse连接", pathUrl, appName)
    const onopen = () => {
        console.log("建立文件数据sse连接成功", pathUrl, appName)
    }
    const fileName = editFileId || 'readme'
    // 建立连接
    let sseChatParams: SSEChatParams = {
        onopen,
        url: setUrlParams(pathUrl, fileName),
        onmessage: (event: MessageEvent) => {
            console.log('收到文件内容消息：', event.data);
            if (event.data) {
                const dataObj = JSON.parse(event.data)
                updateFileData(dataObj);
                sseData.value = sseData.value ? [...sseData.value, dataObj] : [dataObj]
            }
        },
        finallyHandler: () => {
            console.log("finallyHandler操作")
        }
    };
    sseService.connect(sseChatParams)
}

const formatSheetDataString = (sheetDataString: any) => {
    const dataList = sheetDataString.split('\n').map((line:any) =>line.split(';').slice(1)).slice(1)
    console.log('格式化数据', sheetDataString, dataList)
    const decodedDataList = dataList.map((row:any) => row.map((cell:any) => decodeString(cell)))
    return decodedDataList
}
/**
 * 将同key的value信息和setting信息合并
 */
const mergeSheetData = (sheetDataList: [], sheetSetting: any) => {
    return { ...sheetSetting, data: sheetDataList }
}

/**
 * 将数据合并到fileData中
 * 有同key则更新（弃用旧的，使用传入的这个），没有则在fileData中添加该条数据
 * @param item 
 */
const updateFileDataItem = (item:any) => {
    if(fileData.value) {
        const index = fileData.value?.findIndex((element:any) => element.key === item.key);
        if (index !== -1) {
            fileData.value[index] = item
        } else {
            fileData.value = [...fileData.value, item]
        }
    } else {
        fileData.value = [item]
    }
}
/**
 * 将sse数据合并到fileData
 * 如果是setting类型的item：如果对应key的value数据已存在，则合并数据，并更新file的setting数据。否则不理会。
 * 如果是value类型的item：如果对应key的setting数据已存在，则合并数据，并更新file的setting数据。否则将该条数据直接添加到fileData中。
 * @param item ：当条数据
 */
const updateFileData = (item: any) => {
    const key = item.key
    const value = item.value
    if (value) { // 如果是value类型的item
        // 如果已经有过value数据，则合并数据
        const valueItems = sseData.value?.filter(element => element.key === key && element.value).flatMap(element => formatSheetDataString(element.value));
        const currentValueArray = formatSheetDataString(value)
        // console.log('合并数据', valueItems, currentValueArray)
        const newValueArray = valueItems?.length ? [...valueItems, ...currentValueArray] : currentValueArray
        const settingItem = sseData.value?.find(element => element.key === key && element.setting)
        if (settingItem) {
            updateFileDataItem(mergeSheetData(newValueArray, settingItem))
        }
    } else { // 如果是setting类型的item
        const valueItem = sseData.value?.find(element => element.key === key && element.value)
        if (valueItem) {
            updateFileDataItem(mergeSheetData(item, valueItem))
        } else {
            fileData.value = fileData.value ? [...fileData.value, item] : [item]
        }
    }
}

onMounted(() => {
    if (mode === 'update') {
        sseServiceOpen()
    }
});
onUnmounted(() => {
    if (mode === 'update') {
        sseService.disconnect()
    }
})
</script>
<template>
    <ComponentsExcel :fileData :mode :currentApp :editFileName />
</template>
<style scoped></style>